package org.os.framework.context.config;

import java.util.Objects;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring上下文
 * 
 * @author
 */
@Component
public class SpringContext implements ApplicationContextAware {

    /**
     * 禁止通过new进行实例化
     */
    private SpringContext() {
    }

    private static ApplicationContext context;

    public static void setContext(ApplicationContext context) {
        if (Objects.isNull(SpringContext.context)) {
            SpringContext.context = context;
        }
    }

    @SuppressWarnings("null")
    @Override
    public void setApplicationContext(ApplicationContext context) {
        SpringContext.setContext(context);
    }

    /**
     * 获取上下文
     * 
     * @return
     */
    public static ApplicationContext getContext() {
        return SpringContext.context;
    }

    /**
     * 根据名称获取bean
     * 
     * @param <E>
     * @param beanName
     * @return
     */
    @SuppressWarnings({ "unchecked" })
    public static <E> E getBean(String beanName) {
        if (null == beanName) {
            return null;
        }
        return Objects.nonNull(context) ? (E) context.getBean(beanName) : null;
    }

    /**
     * 根据类型获取bean
     * 
     * @param <E>
     * @param beanClass
     * @return
     */
    public static <E> E getBean(Class<E> beanClass) {
        if (null == beanClass) {
            return null;
        }
        return Objects.nonNull(context) ? context.getBean(beanClass) : null;
    }

}
